package com.tedu.charging.service.bill.config;

import com.alibaba.fastjson2.JSONObject;
import com.tedu.charging.service.bill.pojo.param.DeviceSelfCheckResultParam;
import com.tedu.charging.service.bill.service.IChargingBillService;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

//mqtt客户端配置类
@Configuration
public class MqttConfig {
    @Value("${mqtt.client.username}")
    private String username;
    @Value("${mqtt.client.password}")
    private String password;
    @Value("${mqtt.client.serverURI}")
    private String serverURI;
    @Value("${mqtt.client.clientId}")
    private String clientId;

    MqttClient mqttClient;
    @Autowired
    private IChargingBillService chargingBillService;

    @Bean
    public MqttClient mqttClient() {
        try {
            mqttClient = new MqttClient(serverURI, clientId);

            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            options.setCleanSession(true);
            options.setAutomaticReconnect(true);
            options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);

            //添加回调，用来订阅emqx信息
            mqttClient.setCallback(new MqttCallback());

            mqttClient.connect(options);

            return mqttClient;
        } catch (MqttException e) {
            System.out.println("emq connect error" + e);
            return null;
        }
    }

    //内部类，用来订阅emqx的信息
    class MqttCallback implements MqttCallbackExtended {

        //断开连接时，由mqtt客户端框架自动调用
        @Override
        public void connectionLost(Throwable throwable) {
            System.out.println("emq error.");
            throwable.printStackTrace();
        }

        //收到消息时，由mqtt客户端框架自动调用

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            //处理消息
            System.out.println("收到消息");
            DeviceSelfCheckResultParam deviceSelfCheckResultParam = JSONObject.parseObject(message.toString(), DeviceSelfCheckResultParam.class);

            if (deviceSelfCheckResultParam.getCheckResult().equals("start charging success")) {
                chargingBillService.chagringSuccess(deviceSelfCheckResultParam.getBillId());
            } else {
                chargingBillService.chagringFail(deviceSelfCheckResultParam.getBillId());
            }

            System.out.println(message);

        }

        // 发送消息完成后执行
        @Override
        public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {


        }

        //连接emqx完成时，由mqtt客户端框架自动调用
        @Override
        public void connectComplete(boolean b, String s) {
            //和EMQ连接成功后根据配置自动订阅topic
            try {
                mqttClient.subscribe("topic/startchargingResult", 0);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }

    }
}

